import type { Conversation, Message, Profile } from 'tim-js-sdk'
import { defineStore } from 'pinia'
import TIM from 'tim-js-sdk'
import imAPI from '/@/api/im/index'

export interface IMState {
  tim: any
  isReady: boolean
  isLoggedIn: boolean
  currentUser: Profile | null
  conversationList: Conversation[]
  currentConversation: Conversation | null
  messageList: Message[]
  unreadCount: number
  contactList: Profile[]
  pendingUserInfo: { nick?: string; avatar?: string; selfSignature?: string } | null // 待设置的用户信息
  isLoadingMoreMessages: boolean
  hasMoreMessages: boolean  
  nextReqMessageID: string
}

export const useIMStore = defineStore('im', {
  state: (): IMState => ({
    tim: null,
    isReady: false,
    isLoggedIn: false,
    currentUser: null,
    conversationList: [],
    currentConversation: null,
    messageList: [],
    unreadCount: 0,
    contactList: [],
    pendingUserInfo: null,
    isLoadingMoreMessages: false,
    hasMoreMessages: true,
    nextReqMessageID: '',
  }),

  getters: {
    // 获取当前会话ID
    currentConversationID(): string {
      return this.currentConversation?.conversationID || ''
    },

    // 获取未读消息总数
    totalUnreadCount(): number {
      return this.conversationList.reduce((total, conversation) => {
        return total + (conversation.unreadCount || 0)
      }, 0)
    },

    // 获取当前会话的消息列表
    currentMessages(): Message[] {
      return this.messageList
    },
  },

  actions: {
    // 初始化IM SDK
    async initIM(sdkAppID: number) {
      try {
        // 创建 SDK 实例
        this.tim = TIM.create({
          SDKAppID: sdkAppID,
        })

        // 设置日志级别
        this.tim.setLogLevel(0) // 0: 普通级别，日志量较多

        // 注册事件监听器
        this.registerEventListeners()

        this.isReady = true
        console.log('IM SDK 初始化成功')
        return { code: 0, message: 'IM SDK 初始化成功' }
      }
      catch (error) {
        console.error('IM SDK 初始化失败:', error)
        return { code: -1, message: `IM SDK 初始化失败: ${error}` }
      }
    },
    // 注册事件监听器
    registerEventListeners() {
      if (!this.tim) { return }

      // SDK 进入 ready 状态
      this.tim.on(TIM.EVENT.SDK_READY, this.onSDKReady)

      // SDK 进入 not ready 状态
      this.tim.on(TIM.EVENT.SDK_NOT_READY, this.onSDKNotReady)

      // 收到推送的单聊、群聊、群提示、群系统通知的新消息
      this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived)

      // 会话列表更新
      this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated)

      // 用户被踢下线
      this.tim.on(TIM.EVENT.KICKED_OUT, this.onKickedOut)

      // 网络状态发生改变
      this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange)
    },

    // SDK ready 事件处理
    onSDKReady() {
      console.log('SDK 进入 ready 状态')
      this.isLoggedIn = true
      // 获取个人资料
      this.getMyProfile()
      // 获取会话列表
      this.getConversationList()
      // 获取好友列表
      // this.getContactList()
      
      // 如果有待设置的用户信息，现在设置
      if (this.pendingUserInfo) {
        console.log('SDK Ready，开始设置待处理的用户信息:', this.pendingUserInfo)
        this.setUserBasicInfo(this.pendingUserInfo).then(result => {
          console.log('SDK Ready时设置用户信息结果:', result)
          // 清空待处理信息
          this.pendingUserInfo = null
        }).catch(error => {
          console.error('SDK Ready时设置用户信息失败:', error)
        })
      }
    },

    // SDK not ready 事件处理
    onSDKNotReady() {
      console.log('SDK 进入 not ready 状态')
      this.isLoggedIn = false
    },

    // 收到新消息
    onMessageReceived(event: any) {
      console.log('收到新消息:', event.data)
      // 如果是当前会话的消息，添加到消息列表
      const messages = event.data
      messages.forEach((message: Message) => {
        if (message.conversationID === this.currentConversationID) {
          this.messageList.push(message)
        }
      })
    },

    // 会话列表更新
    onConversationListUpdated(event: any) {
      console.log('会话列表更新:', event.data)
      this.conversationList = event.data
      this.updateUnreadCount()
    },

    // 用户被踢下线
    onKickedOut(event: any) {
      console.log('用户被踢下线:', event.data)
      this.logout()
    },

    // 网络状态变化
    onNetStateChange(event: any) {
      console.log('网络状态变化:', event.data)
    },

    // 登录
    async login(userID: string, userSig: string) {
      if (!this.tim) {
        return { code: -1, message: 'IM SDK 未初始化' }
      }

      try {
        console.log('正在登录...:', { userID, userSig })
        const res = await this.tim.login({ userID, userSig })
        console.log('登录成功:', res)
        return res
      }
      catch (error) {
        console.error('登录失败:', error)
        return { code: -1, message: `登录失败: ${error}` }
      }
    },

    // 登出
    async logout() {
      if (!this.tim) { return }

      try {
        const res = await this.tim.logout()
        console.log('登出成功:', res)

        // 清空状态
        this.isLoggedIn = false
        this.currentUser = null
        this.conversationList = []
        this.currentConversation = null
        this.messageList = []
        this.unreadCount = 0
        this.contactList = []

        return res
      }
      catch (error) {
        console.error('登出失败:', error)
        return { code: -1, message: `登出失败: ${error}` }
      }
    },

    // 获取会话列表
    async getConversationList() {
      if (!this.tim) { return }

      try {
        const res = await this.tim.getConversationList()
        if (res.code === 0) {
          this.conversationList = res.data.conversationList
          this.updateUnreadCount()
        }
        return res
      }
      catch (error) {
        console.error('获取会话列表失败:', error)
      }
    },

    // 获取好友列表
    async getContactList() {
      if (!this.tim) { return }

      try {
        const res = await this.tim.getFriendList()
        if (res.code === 0) {
          this.contactList = res.data.friendList
        }
        return res
      }
      catch (error) {
        console.error('获取好友列表失败:', error)
      }
    },

    // 设置当前会话
    async setCurrentConversation(conversation: Conversation) {
      this.currentConversation = conversation
      // 获取该会话的消息列表
      await this.getMessageList(conversation.conversationID, '')
      // 将该会话设为已读
      await this.setMessageRead(conversation.conversationID)
    },
    // 删除全部消息
    async deleteAllMessages(conversationID: string) {
      if (!this.tim) {
        console.error('IM未初始化')
        return { code: -1, message: 'IM未初始化' }
      }

      try {

        let promise = this.tim.deleteConversation(conversationID);
        promise.then(function(imResponse:any) {
          console.log(imResponse.data); // 删除成功
        }); 
      } catch (error) {
        console.error('删除全部消息失败:', error)
        return { code: -1, message: '删除全部消息失败' }
      }
    },

    // 获取消息列表
    async getMessageList(conversationID: string, nextReqMessageID?: string) {
      console.log('获取数据啦')
      if (!this.tim) { return }

      try {
        const res = await this.tim.getMessageList({
          conversationID,
          nextReqMessageID,
          count: 15,
        })
        console.log('消息列表:', res)
        if (res.code === 0) {
          const messages = res.data.messageList
          // console.log('messages:', messages)
          // console.log('消息列表nextReqMessageID:', nextReqMessageID)
          if (res.data.isCompleted) {
            // console.log('没有更多消息了')
            this.hasMoreMessages = false
          }else {
            // console.log('还有更多消息')
            this.hasMoreMessages = true
          }
          if (nextReqMessageID) {
            // 加载更多消息，插入到列表前面
            // SDK返回的是倒序（最新在前），我们需要反转后插入到前面
            const newMessages = messages.reverse()
            
            // 去重：过滤掉已存在的消息
            const existingMessageIds = new Set(this.messageList.map(msg => msg.ID))
            // 按时间戳升序排序
            const uniqueNewMessages = newMessages.filter((msg:any) => !existingMessageIds.has(msg.ID)).sort((a:any, b:any) => a.time - b.time) 
            
            // 只插入不重复的消息
            this.messageList.unshift(...uniqueNewMessages)
          } else {
            // 首次加载消息
            const latestMessages = messages.slice(0, 15)
            console.log("latestMessages:", latestMessages)
            // SDK返回的是倒序（最新在前），反转后最新的在后面
            this.messageList = latestMessages.reverse()

            // 确保消息按时间正序排列（最新的在最后）
            this.messageList.sort((a, b) => {
              const timeA = a.time || 0
              const timeB = b.time || 0
              return timeA - timeB
            })
          }
           
          this.nextReqMessageID = res.data.nextReqMessageID
        }
        return res
      }
      catch (error) {
        console.error('获取消息列表失败:', error)
      }
    },

    // 发送文本消息
    async sendTextMessage(text: string, to: string, conversationType: string = TIM.TYPES.CONV_C2C) {
      console.log('发送文本消息:', text, to, conversationType)
      if (!this.tim) { return }

      try {
        // 创建文本消息
        const message = this.tim.createTextMessage({
          to,
          conversationType,
          payload: {
            text,
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送消息失败:', error)
        return { code: -1, message: `发送消息失败: ${error}` }
      }
    },

    // 发送图片消息
    async sendImageMessage(file: File, to: string, conversationType: string = TIM.TYPES.CONV_C2C) {
      if (!this.tim) { return }

      try {
        // 创建图片消息
        const message = this.tim.createImageMessage({
          to,
          conversationType,
          payload: {
            file,
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送图片消息失败:', error)
        return { code: -1, message: `发送图片消息失败: ${error}` }
      }
    },

    // 发送自定义消息
    async sendCustomMessage(data: any, description: string, to: string, conversationType: string = TIM.TYPES.CONV_C2C) {
      console.log('发送自定义消息:', data, description, to, conversationType)
      console.log(this.tim)
      if (!this.tim) { return }

      try {
        // 创建自定义消息
        const message = this.tim.createCustomMessage({
          to,
          conversationType,
          payload: {
            data: JSON.stringify(data),
            description, // 离线推送显示的文本
            extension: data.type || 'custom', // 消息类型标识
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送自定义消息失败:', error)
        return { code: -1, message: `发送自定义消息失败: ${error}` }
      }
    },

    // 发送位置消息
    async sendLocationMessage(description: string, longitude: number, latitude: number, to: string, conversationType: string = TIM.TYPES.CONV_C2C) {
      console.log('发送位置消息:', description, longitude, latitude, to, conversationType)
      if (!this.tim) { return }

      try {
        // 创建位置消息
        const message = this.tim.createLocationMessage({
          to,
          conversationType,
          payload: {
            description,
            longitude,
            latitude,
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送位置消息失败:', error)
        return { code: -1, message: `发送位置消息失败: ${error}` }
      }
    },
    // 发送图片类型的自定义消息
    async sendImageCustomMessage(imageUrl: string, imageName: string, to: string, conversationType: string = TIM.TYPES.CONV_C2C) {
      if (!this.tim) { return }

      try {
        const imageData = {
          type: 'image',
          imageUrl,
          imageName,
          timestamp: Date.now(),
        }

        // 创建自定义消息
        const message = this.tim.createCustomMessage({
          to,
          conversationType,
          payload: {
            data: JSON.stringify(imageData),
            description: '[图片]', // 离线推送显示的文本
            extension: 'image', // 消息类型标识
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送图片自定义消息失败:', error)
        return { code: -1, message: `发送图片自定义消息失败: ${error}` }
      }
    },

    // 发送文件类型自定义消息
    async sendFileCustomMessage(fileUrl: string, fileName: string, fileSize: number, to: string, conversationType: string) {
      if (!this.tim) {
        return { code: -1, message: 'IM SDK未初始化' }
      }

      try {
        const fileData = {
          type: 'file',
          fileUrl,
          fileName,
          fileSize,
          timestamp: Date.now(),
        }

        // 创建自定义消息
        const message = this.tim.createCustomMessage({
          to,
          conversationType,
          payload: {
            data: JSON.stringify(fileData),
            description: `[文件] ${fileName}`, // 离线推送显示的文本
            extension: 'file', // 消息类型标识
          },
        })

        // 发送消息
        const res = await this.tim.sendMessage(message)
        if (res.code === 0) {
          // 发送成功，将消息添加到当前消息列表
          if (message.conversationID === this.currentConversationID) {
            this.messageList.push(message)
          }
        }
        return res
      }
      catch (error) {
        console.error('发送文件自定义消息失败:', error)
        return { code: -1, message: `发送文件自定义消息失败: ${error}` }
      }
    },

    // 将消息设为已读
    async setMessageRead(conversationID: string) {
      if (!this.tim) { return }

      try {
        const res = await this.tim.setMessageRead({ conversationID })
        if (res.code === 0) {
          // 更新会话列表中的未读数
          const conversation = this.conversationList.find(conv => conv.conversationID === conversationID)
          if (conversation) {
            conversation.unreadCount = 0
          }
          this.updateUnreadCount()
        }
        return res
      }
      catch (error) {
        console.error('设置消息已读失败:', error)
      }
    },

    // 更新未读消息数
    updateUnreadCount() {
      this.unreadCount = this.totalUnreadCount
    },

    // 销毁 SDK 实例
    destroy() {
      if (this.tim) {
        this.tim.destroy()
        this.tim = null
        this.isReady = false
        this.isLoggedIn = false
        this.currentUser = null
        this.conversationList = []
        this.currentConversation = null
        this.messageList = []
        this.unreadCount = 0
        this.contactList = []
      }
    },

    // 自动重连IM（用于页面刷新后恢复连接）
    async autoReconnect() {
      try {
        // 检查是否已经连接
        if (this.isLoggedIn && this.tim) {
          console.log('IM 已连接，无需重连')
          return { code: 0, message: 'IM 已连接' }
        }

        // 检查用户是否已登录系统
        const token = localStorage.getItem('token')
        if (!token) {
          console.log('用户未登录系统，跳过IM重连')
          return { code: -1, message: '用户未登录系统' }
        }

        // 获取IM配置信息
        const imConfigInfo = await this.getIMConfig()
        if (!imConfigInfo || !imConfigInfo.sdkAppID) {
          console.warn('IM配置信息不完整，跳过重连')
          return { code: -1, message: 'IM配置信息不完整' }
        }

        // 初始化IM SDK
        if (!this.tim) {
          const initResult = await this.initIM(imConfigInfo.sdkAppID)
          if (initResult.code !== 0) {
            console.error('IM SDK 重新初始化失败:', initResult.message)
            return initResult
          }
        }

        // 执行IM登录
        const userID = imConfigInfo.userID.toString()
        const userSig = imConfigInfo.userSig
        const loginResult = await this.login(userID, userSig)

        if (loginResult.code === 0) {
          console.log('IM 自动重连成功')
          return { code: 0, message: 'IM 自动重连成功' }
        }
        else {
          console.error('IM 自动重连失败:', loginResult.message)
          return loginResult
        }
      }
      catch (error) {
        console.error('IM 自动重连异常:', error)
        return { code: -1, message: `IM 自动重连异常: ${error}` }
      }
    },

    // 获取IM配置信息（从服务端或本地存储）
    async getIMConfig() {
      try {
        // 动态导入IM API模块
        // const imAPI = await import('/@/api/im/index')

        // 优先从服务端获取
        const response = await imAPI.getUserSign()
        if (response.data && response.data.userSig) {
          return {
            userSig: response.data.userSig,
            sdkAppID: response.data.sdkAppId,
            userID: response.data.userId,
          }
        }
      }
      catch (error) {
        console.warn('从服务端获取IM配置失败:', error)
      }

      // 备用方案：从本地存储获取
      try {
        const account = localStorage.getItem('account')
        if (account) {
          const storedConfig = localStorage.getItem(`im_config_${account}`)
          if (storedConfig) {
            return JSON.parse(storedConfig)
          }
        }
      }
      catch (error) {
        console.warn('从本地存储获取IM配置失败:', error)
      }

      return null
    },

    // 初始化假数据（用于演示）
    initMockData() {
      // 模拟当前用户
      this.currentUser = {
        userID: 'user001',
        nick: '当前用户',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        gender: 1,
        birthday: 0,
        location: '',
        language: 0,
        messageSettings: 0,
        adminForbidType: 0,
        level: 0,
        role: 0,
        lastUpdatedTime: Date.now(),
        profileCustomField: [],
      }

      // 模拟会话列表
      this.conversationList = [
        {
          conversationID: 'C2C_user002',
          type: 1, // C2C
          subType: 0,
          conversationType: 'C2C',
          peerReadTime: 0,
          groupReadSequence: 0,
          unreadCount: 3,
          lastMessage: {
            ID: 'msg001',
            conversationID: 'C2C_user002',
            conversationType: 1,
            to: 'user001',
            from: 'user002',
            flow: 'in',
            time: Date.now() - 300000, // 5分钟前
            status: 'success',
            isRevoked: false,
            priority: 'Normal',
            nick: '张三',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            nameCard: '',
            payload: {
              text: '你好，最近怎么样？',
            },
            cloudCustomData: '',
            type: 'TIMTextElem',
            lastTime: Date.now() - 300000,
          },
          groupProfile: null,
          userProfile: {
            userID: 'user002',
            nick: '张三',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            gender: 1,
            birthday: 0,
            location: '',
            language: 0,
            messageSettings: 0,
            adminForbidType: 0,
            level: 0,
            role: 0,
            lastUpdatedTime: Date.now(),
            profileCustomField: [],
          },
          remark: '',
          isPinned: false,
          muteEndTime: 0,
        },
        {
          conversationID: 'C2C_user003',
          type: 1, // C2C
          subType: 0,
          conversationType: 'C2C',
          peerReadTime: 0,
          groupReadSequence: 0,
          unreadCount: 1,
          lastMessage: {
            ID: 'msg002',
            conversationID: 'C2C_user003',
            conversationType: 1,
            to: 'user001',
            from: 'user003',
            flow: 'in',
            time: Date.now() - 600000, // 10分钟前
            status: 'success',
            isRevoked: false,
            priority: 'Normal',
            nick: '李四',
            avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
            nameCard: '',
            payload: {
              text: '明天的会议准备好了吗？',
            },
            cloudCustomData: '',
            type: 'TIMTextElem',
            lastTime: Date.now() - 600000,
          },
          groupProfile: null,
          userProfile: {
            userID: 'user003',
            nick: '李四',
            avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
            gender: 1,
            birthday: 0,
            location: '',
            language: 0,
            messageSettings: 0,
            adminForbidType: 0,
            level: 0,
            role: 0,
            lastUpdatedTime: Date.now(),
            profileCustomField: [],
          },
          remark: '',
          isPinned: false,
          muteEndTime: 0,
        },
        {
          conversationID: 'GROUP_group001',
          type: 2, // GROUP
          subType: 0,
          conversationType: 'GROUP',
          peerReadTime: 0,
          groupReadSequence: 0,
          unreadCount: 5,
          lastMessage: {
            ID: 'msg003',
            conversationID: 'GROUP_group001',
            conversationType: 2,
            to: 'group001',
            from: 'user004',
            flow: 'in',
            time: Date.now() - 180000, // 3分钟前
            status: 'success',
            isRevoked: false,
            priority: 'Normal',
            nick: '王五',
            avatar: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48png.png',
            nameCard: '',
            payload: {
              text: '大家好，项目进展如何？',
            },
            cloudCustomData: '',
            type: 'TIMTextElem',
            lastTime: Date.now() - 180000,
          },
          groupProfile: {
            groupID: 'group001',
            name: '项目讨论组',
            avatar: 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png',
            type: 'Public',
            introduction: '项目相关讨论',
            notification: '',
            ownerID: 'user005',
            createTime: Date.now() - 86400000,
            memberCount: 8,
            maxMemberCount: 200,
            joinOption: 'FreeAccess',
            muteAllMembers: false,
          },
          userProfile: null,
          remark: '',
          isPinned: true,
          muteEndTime: 0,
        },
      ]

      // 模拟好友列表
      this.contactList = [
        {
          userID: 'user002',
          nick: '张三',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          gender: 1,
          birthday: 0,
          location: '',
          language: 0,
          messageSettings: 0,
          adminForbidType: 0,
          level: 0,
          role: 0,
          lastUpdatedTime: Date.now(),
          profileCustomField: [],
        },
        {
          userID: 'user003',
          nick: '李四',
          avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
          gender: 1,
          birthday: 0,
          location: '',
          language: 0,
          messageSettings: 0,
          adminForbidType: 0,
          level: 0,
          role: 0,
          lastUpdatedTime: Date.now(),
          profileCustomField: [],
        },
      ]

      // 模拟消息列表（为第一个会话）
      this.messageList = [
        {
          ID: 'msg_001',
          conversationID: 'C2C_user002',
          conversationType: 1,
          to: 'user001',
          from: 'user002',
          flow: 'in',
          time: Date.now() - 3600000, // 1小时前
          status: 'success',
          isRevoked: false,
          priority: 'Normal',
          nick: '张三',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          nameCard: '',
          payload: {
            text: '你好！',
          },
          cloudCustomData: '',
          type: 'TIMTextElem',
        },
        {
          ID: 'msg_002',
          conversationID: 'C2C_user002',
          conversationType: 1,
          to: 'user002',
          from: 'user001',
          flow: 'out',
          time: Date.now() - 3500000, // 58分钟前
          status: 'success',
          isRevoked: false,
          priority: 'Normal',
          nick: '当前用户',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          nameCard: '',
          payload: {
            text: '你好！很高兴认识你。',
          },
          cloudCustomData: '',
          type: 'TIMTextElem',
        },
        {
          ID: 'msg_003',
          conversationID: 'C2C_user002',
          conversationType: 1,
          to: 'user001',
          from: 'user002',
          flow: 'in',
          time: Date.now() - 1800000, // 30分钟前
          status: 'success',
          isRevoked: false,
          priority: 'Normal',
          nick: '张三',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          nameCard: '',
          payload: {
            text: '我也很高兴认识你！最近在忙什么项目？',
          },
          cloudCustomData: '',
          type: 'TIMTextElem',
        },
        {
          ID: 'msg_004',
          conversationID: 'C2C_user002',
          conversationType: 1,
          to: 'user002',
          from: 'user001',
          flow: 'out',
          time: Date.now() - 900000, // 15分钟前
          status: 'success',
          isRevoked: false,
          priority: 'Normal',
          nick: '当前用户',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          nameCard: '',
          payload: {
            text: '最近在做一个管理系统，集成了即时通信功能。',
          },
          cloudCustomData: '',
          type: 'TIMTextElem',
        },
        {
          ID: 'msg_005',
          conversationID: 'C2C_user002',
          conversationType: 1,
          to: 'user001',
          from: 'user002',
          flow: 'in',
          time: Date.now() - 300000, // 5分钟前
          status: 'success',
          isRevoked: false,
          priority: 'Normal',
          nick: '张三',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          nameCard: '',
          payload: {
            text: '听起来很有趣！可以分享一下技术细节吗？',
          },
          cloudCustomData: '',
          type: 'TIMTextElem',
        },
      ]

      // 不自动设置当前会话，让用户手动选择
      this.currentConversation = null

      // 清空消息列表，只有选择会话后才加载消息
      this.messageList = []

      // 更新状态
      this.isLoggedIn = true
      this.updateUnreadCount()

      console.log('IM 假数据初始化完成')
    },

    // 清除假数据
    clearMockData() {
      this.currentUser = null
      this.conversationList = []
      this.currentConversation = null
      this.messageList = []
      this.unreadCount = 0
      this.contactList = []
      console.log('IM 假数据已清除')
    },

    // 获取个人资料
    async getMyProfile() {
      if (!this.tim) { return }

      try {
        const res = await this.tim.getMyProfile()
        if (res.code === 0) {
          this.currentUser = res.data
        }
        return res
      }
      catch (error) {
        console.error('获取个人资料失败:', error)
      }
    },

    // 设置个人资料
    async updateMyProfile(profileData: {
      nick?: string
      avatar?: string
      gender?: number
      birthday?: number
      location?: string
      selfSignature?: string
      allowType?: string
      language?: number
      profileCustomField?: Array<{ key: string; value: string }>
    }) {
      if (!this.tim) { 
        return { code: -1, message: 'IM SDK 未初始化' }
      }

      try {
        console.log('正在更新个人资料:', profileData)
        const res = await this.tim.updateMyProfile(profileData)
        
        if (res.code === 0) {
          // 更新成功后重新获取个人资料
          await this.getMyProfile()
          console.log('个人资料更新成功')
        }
        
        return res
      }
      catch (error) {
        console.error('更新个人资料失败:', error)
        return { code: -1, message: `更新个人资料失败: ${error}` }
      }
    },

    // 设置基本用户信息（登录后调用）
    async setUserBasicInfo(userInfo: {
      nick?: string
      avatar?: string
      selfSignature?: string
    }) {

      console.log('设置基本用户信息（登录后调用）:', userInfo)
      console.log('IM状态检查 - tim:', !!this.tim, 'isLoggedIn:', this.isLoggedIn)
      
      if (!this.tim || !this.isLoggedIn) {
        console.warn('IM未登录，跳过设置用户信息')
        console.warn('详细状态 - tim存在:', !!this.tim, 'isLoggedIn:', this.isLoggedIn)
        return { code: -1, message: 'IM未登录' }
      }

      console.log('IM状态正常，开始设置用户信息')

      try {
        // 构建更新数据，只包含有值的字段
        const updateData: any = {}
        
        if (userInfo.nick) {
          updateData.nick = userInfo.nick
        }
        
        if (userInfo.avatar) {
          updateData.avatar = userInfo.avatar
        }
        
        if (userInfo.selfSignature) {
          updateData.selfSignature = userInfo.selfSignature
        }
        console.log('构建更新数据完成:', updateData)

        // 如果没有要更新的数据，直接返回
        if (Object.keys(updateData).length === 0) {
          console.log('没有需要更新的用户信息')
          return { code: 0, message: '没有需要更新的信息' }
        }

        console.log('设置用户基本信息:', updateData)
        const result = await this.updateMyProfile(updateData)
        
        if (result.code === 0) {
          console.log('用户基本信息设置成功')
        } else {
          console.error('用户基本信息设置失败:', result.message)
        }
        
        return result
      }
      catch (error) {
        console.error('设置用户基本信息异常:', error)
        return { code: -1, message: `设置用户基本信息异常: ${error}` }
      }
    },

    // 设置待处理的用户信息（在SDK Ready前调用）
    setPendingUserInfo(userInfo: {
      nick?: string
      avatar?: string
      selfSignature?: string
    }) {
      console.log('设置待处理的用户信息:', userInfo)
      this.pendingUserInfo = userInfo
      
      // 如果SDK已经Ready，立即设置
      if (this.isLoggedIn && this.tim) {
        console.log('SDK已Ready，立即设置用户信息')
        this.setUserBasicInfo(userInfo).then(result => {
          console.log('立即设置用户信息结果:', result)
          this.pendingUserInfo = null
        }).catch(error => {
          console.error('立即设置用户信息失败:', error)
        })
      } else {
        console.log('SDK未Ready，用户信息已存储，等待SDK Ready事件')
      }
    },
  },
})
